﻿#if DIRECTSHOW
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DirectShowLib;
using System.Diagnostics;

namespace WhatsPlayingClient.Audio
{
	public class SampleGrabber : ISampleGrabberCB, IDisposable
	{
		public MemoryStream stream { get; private set; }

//		private DirectShowStream parent;

		public ISampleGrabber Filter { get; private set; }

		public SampleGrabber()
		{
			Filter = (DirectShowLib.ISampleGrabber)new DirectShowLib.SampleGrabber();

			DirectShowLib.AMMediaType requestedType = new DirectShowLib.AMMediaType();
			requestedType.majorType = DirectShowLib.MediaType.Audio;
			requestedType.subType = DirectShowLib.MediaSubType.PCM;
			Filter.SetMediaType(requestedType);

			DirectShowLib.DsUtils.FreeAMMediaType(requestedType);

			Filter.SetCallback(this, 1);
			this.stream = new MemoryStream();
		}

//        public SampleGrabber(/*DirectShowStream parent*/)
//            : this()
//        {
//            this.stream = new MemoryStream();
//			this.parent = parent;   // allows access to the mediaControl and position
//        }

		public int BufferCB(double time, IntPtr ptr, int length)
		{
			if (stream == null) return length;

			byte[] data = new byte[length];
			System.Runtime.InteropServices.Marshal.Copy(ptr, data, 0, length);

			if (System.Threading.Monitor.TryEnter(stream, 50))
			{
				stream.Seek(0, SeekOrigin.End);
				stream.Write(data, 0, length);

				System.Threading.Monitor.Exit(stream);
			}
			else
				Trace.WriteLine("BufferCB could not get a lock.");

			return length;
		}

		public int SampleCB(double time, DirectShowLib.IMediaSample sample)
		{
			return 0;
		}

		#region IDisposable
		public void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (stream != null)
				{
					stream.Dispose();
					stream = null;
				}
			}
		}

		public void Dispose()
		{
			Dispose(true);
		}
		#endregion
	}
}
#endif